package cn.cheniy.swiftmark.rbac.feign;

import cn.cheniy.swiftmark.api.rbac.bo.UriPermissionBO;
import cn.cheniy.swiftmark.api.rbac.dto.ClearUserPermissionsCacheDTO;
import cn.cheniy.swiftmark.api.rbac.feign.PermissionFeignClient;
import cn.cheniy.swiftmark.common.response.ResponseEnum;
import cn.cheniy.swiftmark.common.response.ServerResponseEntity;
import cn.cheniy.swiftmark.common.util.BooleanUtil;
import cn.cheniy.swiftmark.rbac.service.MenuPermissionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

/**
 * @author cheniy
 * @description
 *
 */
@RestController
public class PermissionFeignController implements PermissionFeignClient {

    private static final Logger logger = LoggerFactory.getLogger(PermissionFeignController.class);

    @Autowired
    private MenuPermissionService menuPermissionService;


    /**
     * 查询用户在该系统下访问uir是否有权限
     * @param userId
     * @param sysType
     * @param uri
     * @param isAdmin
     * @param method
     * @return
     */
    @Override
    public ServerResponseEntity<Boolean> checkPermission(@RequestParam ("userId") Long userId, @RequestParam("sysType") Integer sysType, @RequestParam("uri") String uri, @RequestParam("isAdmin") Integer isAdmin, @RequestParam("method") Integer method) {
        // 目前该用户拥有的权限
        List<String> userPermissions = menuPermissionService.listUserPermissions(userId,
                sysType, BooleanUtil.isTrue(isAdmin));

        // 获取到该系统类型中所有的权限
        List<UriPermissionBO> uriPermissions = menuPermissionService.listUriPermissionInfo(sysType);
        // 用于进行 URI 路径的匹配操作。
        AntPathMatcher pathMatcher = new AntPathMatcher();

        // 看看访问该uri需要什么权限
        for (UriPermissionBO uriPermission : uriPermissions) {
            // 查看需要访问的页面是否在系统类型中
            if (pathMatcher.match(uriPermission.getUri(), uri) && Objects.equals(uriPermission.getMethod(), method)) {
                // uri 用户有这个权限
                if (userPermissions.contains(uriPermission.getPermission())) {
                    return ServerResponseEntity.success(Boolean.TRUE);
                }
                else {
                    return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
                }
            }
        }

        // 如果uri 没有匹配到，则说明uri不需要权限，直接校验成功
        return ServerResponseEntity.success(Boolean.TRUE);
    }

    @Override
    public ServerResponseEntity<Void> clearUserPermissionsCache(ClearUserPermissionsCacheDTO clearUserPermissionsCacheDTO) {
        menuPermissionService.clearUserPermissionsCache(clearUserPermissionsCacheDTO.getUserId(), clearUserPermissionsCacheDTO.getSysType());
        return ServerResponseEntity.success();
    }

}

